package com.lw.common.customview

import android.content.Context
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.AttributeSet
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.widget.LinearLayout
import android.widget.Toast
import androidx.appcompat.widget.AppCompatEditText
import com.lw.common.R

/**
 * 自定义IP EdiText
 */
class IPEditText(context: Context, attrs: AttributeSet?) : LinearLayout(context, attrs) {
    //控件
    private val edit1: AppCompatEditText
    private val edit2: AppCompatEditText
    private val edit3: AppCompatEditText
    private val edit4: AppCompatEditText
    private var text1: String? = null
    private var text2: String? = null
    private var text3: String? = null
    private var text4: String? = null

    init {
        //初始化界面
        LayoutInflater.from(context).inflate(R.layout.custom_edit_text, this)
        //绑定
        edit1 = findViewById(R.id.edit1)
        edit2 = findViewById(R.id.edit2)
        edit3 = findViewById(R.id.edit3)
        edit4 = findViewById(R.id.edit4)
        //初始化函数
        init(context)
    }

    private fun init(context: Context) {
//        监听文本，得到ip段，自动进入下一个输入框

        edit1.addTextChangedListener(object : TextWatcher {
            private var trim: String? = null

            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
                trim = s.toString().trim { it <= ' ' }
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                text1 = s.toString().trim { it <= ' ' }
                if (s.length > 2) {
                    if (text1!!.toInt() > 255) {
                        Toast.makeText(context, "请输入合法的ip地址（0~255）", Toast.LENGTH_LONG).show()
                        edit1.setText(trim)
                        edit1.setSelection(trim!!.length - 1)
                    } else {
                        edit2.isFocusable = true
                        edit2.requestFocus()
                    }
                }
            }

            override fun afterTextChanged(s: Editable) {
                Log.d("", "")
            }
        })

        edit2.addTextChangedListener(object : TextWatcher {
            private var trim: String? = null

            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
                trim = s.toString().trim { it <= ' ' }
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                text2 = s.toString().trim { it <= ' ' }
                if (s.length > 2) {
                    if (text2!!.toInt() > 255) {
                        Toast.makeText(context, "请输入合法的ip地址（0~255）", Toast.LENGTH_LONG).show()
                        edit2.setText(trim)
                        edit2.setSelection(trim!!.length - 1)
                    } else {
                        edit3.isFocusable = true
                        edit3.requestFocus()
                    }
                }
                /*
                 * 输入框为空，删除按键则返回上一个文本框
                 */
                /*
                if (start == 0 && s.length() == 0) {
                    Edit1.setFocusable(true);
                    Edit1.requestFocus();
                }
                */
            }

            override fun afterTextChanged(s: Editable) {
            }
        })

        edit3.addTextChangedListener(object : TextWatcher {
            private var trim: String? = null

            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
                trim = s.toString().trim { it <= ' ' }
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                text3 = s.toString().trim { it <= ' ' }
                if (s.length > 2) {
                    if (text3!!.toInt() > 255) {
                        Toast.makeText(context, "请输入合法的ip地址（0~255）", Toast.LENGTH_LONG).show()
                        edit3.setText(trim)
                        edit3.setSelection(trim!!.length - 1)
                    } else {
                        edit4.isFocusable = true
                        edit4.requestFocus()
                    }
                }
                /*
                 * 当用户需要删除时,此时的EditText为空时,上一个EditText获得焦点
                 */
                /*
                if (start == 0 && s.length() == 0) {
                    Edit2.setFocusable(true);
                    Edit2.requestFocus();
                }
                */
            }

            override fun afterTextChanged(s: Editable) {
            }
        })

        edit4.addTextChangedListener(object : TextWatcher {
            private var trim: String? = null

            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
                trim = s.toString().trim { it <= ' ' }
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                text4 = s.toString().trim { it <= ' ' }
                if (s.length > 2) {
                    if (text4!!.toInt() > 255) {
                        Toast.makeText(context, "请输入合法的ip地址（0~255）", Toast.LENGTH_LONG).show()
                        edit4.setText(trim)
                        edit4.setSelection(trim!!.length - 1)
                    }
                }
                /*
                 * 当用户需要删除时,此时的EditText为空时,上一个EditText获得焦点
                 */
                /*
                if (start == 0 && s.length() == 0) {
                    Edit3.setFocusable(true);
                    Edit3.requestFocus();
                }
                */
            }

            override fun afterTextChanged(s: Editable) {
            }
        })

        /*
         *  监听控件，空值时del键返回上一输入框
         */
        edit2.setOnKeyListener { _, keyCode, _ ->
            if (text2 == null || text2!!.isEmpty()) {
                if (keyCode == KeyEvent.KEYCODE_DEL) {
                    edit1.isFocusable = true
                    edit1.requestFocus()
                    edit1.setSelection(edit1.text?.length!!)
                }
            }
            false
        }
        edit3.setOnKeyListener { _, keyCode, _ ->
            if (text3 == null || text3!!.isEmpty()) {
                if (keyCode == KeyEvent.KEYCODE_DEL) {
                    edit2.isFocusable = true
                    edit2.requestFocus()
                    edit2.setSelection(edit2.text?.length!!)
                }
            }
            false
        }
        edit4.setOnKeyListener { _, keyCode, _ ->
            if (text4 == null || text4!!.isEmpty()) {
                if (keyCode == KeyEvent.KEYCODE_DEL) {
                    edit3.isFocusable = true
                    edit3.requestFocus()
                    edit3.setSelection(edit3.text?.length!!)
                }
            }
            false
        }
    }

    val text: String?
        /**
         * 成员函数，返回整个ip地址
         */
        get() {
            //文本
            val text = if (TextUtils.isEmpty(text1) || TextUtils.isEmpty(text2)
                || TextUtils.isEmpty(text3) || TextUtils.isEmpty(text4)
            ) {
                null
            } else {
                "$text1.$text2.$text3.$text4"
            }
            return text
        }
}
